package com.haohan.cloud.scm.message.api.ctrl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haohan.cloud.scm.api.constant.enums.message.InMailTypeEnum;
import com.haohan.cloud.scm.api.constant.enums.message.MsgActionTypeEnum;
import com.haohan.cloud.scm.api.message.dto.SendInMailMessageDTO;
import com.haohan.cloud.scm.api.message.entity.MessageRecord;
import com.haohan.cloud.scm.api.message.req.InMailModifyReq;
import com.haohan.cloud.scm.api.message.req.QueryMessageReq;
import com.haohan.cloud.scm.api.message.req.SendMessageReq;
import com.haohan.cloud.scm.api.message.vo.MsgInfoVO;
import com.haohan.cloud.scm.common.tools.constant.SingleGroup;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.message.core.MessageCoreService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author dy
 * @date 2020/3/20
 */
@RestController
@AllArgsConstructor
@RequestMapping("/api/msg/message")
public class MessageApiCtrl {

    private final MessageCoreService messageCoreService;

    @GetMapping("/record/page")
    @ApiOperation(value = "查询最近消息记录列表")
    public R<IPage<MsgInfoVO>> findRecordPage(Page<MessageRecord> page, QueryMessageReq req) {
        return RUtil.success(messageCoreService.findPage(page, req));
    }

    @GetMapping("/inMail/fetchInfo")
    @ApiOperation(value = "查询消息记录详情")
    public R<MsgInfoVO> fetchInMailInfo(@Validated({SingleGroup.class}) QueryMessageReq req) {
        return RUtil.success(messageCoreService.fetchInMailInfo(req.getMessageSn()));
    }

    @PostMapping("/inMail/sendPlatform")
    @ApiOperation(value = "平台消息发送")
    public R<String> sendPlatform(@Validated SendMessageReq req) {
        SendInMailMessageDTO send = req.transTo();
        send.setMsgActionType(MsgActionTypeEnum.system);
        send.setInMailType(InMailTypeEnum.notice);
        PigxUser user = SecurityUtils.getUser();
        if (null != user) {
            send.setSenderName(user.getUsername());
        }
        messageCoreService.sendInMailMessage(send);
        return RUtil.success("平台消息发送成功");
    }

    @PostMapping("/inMail/modify")
    @ApiOperation(value = "消息修改")
    public R<Boolean> inMailModify(@Validated InMailModifyReq req) {
        if (messageCoreService.inMailModify(req)) {
            return RUtil.success(true);
        }
        return R.failed("修改操作失败");
    }
}
